package sm.upgrade;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.dam.api.DBDictService;
import sm.dbdict.DBDictUtil;
import sm.dbdict.def.DBDict;
import sm.dbdict.def.Field;
import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;
import sm.util.Util;

public class DisplayUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	private boolean idExist(String id, String displayDbdict) {
		boolean idExist = false;
		Object idObj = template.find("from " + displayDbdict + " where id=?",
				id);
		if (idObj != null) {
			idExist = true;
		}
		return idExist;
	}

	private String getID(String screenId, String action, String displayDbdict) {
		String id = screenId + "_" + action;

		int i = 0;
		while (idExist(id, displayDbdict)) {
			i++;
			id = id + i;
		}

		return id;
	}

	@Override
	public void upgrade() {
		logger.info("Upgrading Display Component ID...");

		String[] displayDbdicts = new String[] { "displayoption",
				"displayevent" };

		for (String displayDbdict : displayDbdicts) {
			Object dbdict = template.get(DBDictService.DBDICT, displayDbdict);
			if (dbdict != null) {
				SMMap dbdictMap = (SMMap) dbdict;
				DBDict des = (DBDict) dbdictMap.get(DBDictService.DESCRIPTOR);
				Field idField = DBDictUtil.getField("id", des.getField());
				if (idField != null) {
					List<Object> displays = template.find("from "
							+ Util.radEntityNameToJava(displayDbdict));
					if (displays != null) {
						for (Object display : displays) {
							SMMap displayMap = (SMMap) display;
							if (displayMap.get("id") == null) {
								String screenId = (String) displayMap
										.get("screen_id");
								String action = (String) displayMap
										.get("action");
								String id = getID(screenId, action,
										displayDbdict);
								displayMap.put("id", id);
								template.update(displayDbdict, displayMap);
							}
						}
					}
				}

			}
		}

		logger.info("  Finished Upgrading Display Component ID.");
	}

}
